const url = require('url')
const { readFile,writeFile } = require('../utils/fileHandel')
const id = require('../utils/idHandel')
const path = require('path')

//查询
const get = function(req,res){
    let {query} = url.parse(req.url,true)
    readFile('./data.json',data=>{
        let readResult = JSON.parse(data).goods
        if(query.id){
            let item = readResult.filter(item=>item.id==query.id)
            res.end(JSON.stringify(item))
        }else{
            if(readResult.length<=query.size){
                res.end(JSON.stringify(readResult))
            }else{
                const begin = Number(query.page-1)*Number(query.size)
                const stop = Number(query.page)*Number(query.size)
                res.end(JSON.stringify(readResult.slice(begin,stop)))
            }
        }
    })
}
//新增
const post = function(req,res){
    let option = ''
    req.on('data',function(chunk){
        option += chunk
    })
    req.on('end',function(){
        let obj = JSON.parse(option)
        obj.id = id()
        readFile(path.join(__dirname,'./data.json'),function(data){
            let readResult = JSON.parse(data).goods
            readResult.push(obj)
            const result = {
                goods:readResult
            }
            writeFile(path.join(__dirname,'./data.json'),String(JSON.stringify(result)),(res)=>console.log(res,'写入成功'))
            res.end('新增成功')
        })
    })
}
//put修改
const put = function(req,res){
    let option = ''
    req.on('data',function(chunk){
        option += chunk
    })
    req.on('end',function(){
        let obj = JSON.parse(option)
        readFile('./data.json',function(data){
            let readResult = JSON.parse(data).goods
            readResult.map(item=>{
                if(item.id == obj.id){
                    obj.good_name && (item['good_name'] = obj.good_name)
                    obj.pic && (item['pic'] = obj.pic)
                    obj.price && (item['price'] = obj.price)
                    obj.desc && (item['desc'] = obj.desc)
                }
            })
            const result = {
                goods:readResult
            }
            writeFile('./data.json',String(JSON.stringify(result)),res=>{console.log('修改成功')})
            res.end('修改成功')
        })
    })
}
//删除
const Del = function(req,res){
    let {query} = url.parse(req.url,true)
    readFile('./data.json',data=>{
        let readResult = JSON.parse(data).goods
        const filterDate = readResult.filter(item=>item.id!=query.id)
        const result = {
            goods:filterDate
        }
        writeFile('./data.json',String(JSON.stringify(result)),res=>{console.log('删除成功')})
        res.end('删除成功')
    })

}

module.exports = {
    get,
    post,
    put,
    Del
}